﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LRT.Nebula.IoC
{
    public class UnityControllerFactory : IDependencyResolver//IControllerFactory
    {
        // <summary>  
        /// 依赖注入容器  
        /// </summary>  
        private UnityContainer unityContainer;

        /// <summary>  
        /// 构造  
        /// </summary>  
        /// <param name="unityContainer">依赖注入容器</param>  
        public UnityControllerFactory(UnityContainer unityContainer)
        {
            this.unityContainer = unityContainer;
        }

        #region IDependencyResolver 成员

        public object GetService(Type serviceType)
        {
            if (serviceType == null)
                return null;

            if (!typeof(IController).IsAssignableFrom(serviceType))//只注入控制器
                return null;

            try
            {
                return unityContainer.Resolve(serviceType);
            }
            catch (Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif

                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return unityContainer.ResolveAll(serviceType);
            }
            catch (Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                return new List<object>();
            }
        }

        #endregion
    }
}